kotlin lambdas.md
📅 2026-02-07 👤 hanasaki 🏷️ kotlin

kotlin lambda 表达式

AI 总结
NOTE

Kotlin functions are first-class, which means they can be stored in variables and data structures, and can be passed as arguments to and returned from other higher-order functions. You can perform any operations on functions that are possible for other non-function values.

高阶函数

高阶函数是指以函数作为参数或返回函数的函数。一个典型的例子是集合的fold函数:

kotlin
fun <T, R> Collection<T>.fold(
	initial: R,
	combine: (acc: R, nextElement: T) -> R
): R {
	var accumulator: R = initial
	for (element: in this) {
		accumulator = combine(accumulator, element)
	}
	return accumulator
}

要调用fold可以通过将lambda表达式作为参数传递给它

kotlin
fun main() {
    val items = listOf("1", "2", "3", "4", "5", "6")
    val result = items.fold(0, { acc, next ->
        acc + next.toInt()
    })
    println(items)
    println(result)
}
EXPLORER
Enanamia